package cn.deali.homework9.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jaeger.library.StatusBarUtil;

import java.util.List;

import cn.deali.homework9.R;
import cn.deali.homework9.adapter.OnlineMusicAdapter;
import cn.deali.homework9.model.OnlineMusic;
import cn.deali.homework9.utils.OnlineMusicUtils;

public class OnlineMusicAlbumActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    String name;
    int idx;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            List<OnlineMusic> onlineMusics = (List<OnlineMusic>) msg.obj;
            OnlineMusicAdapter adapter = new OnlineMusicAdapter(OnlineMusicAlbumActivity.this, onlineMusics, name);
            recyclerView.setAdapter(adapter);

            //设置layout manager，默认垂直分布
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(OnlineMusicAlbumActivity.this);
            recyclerView.setLayoutManager(linearLayoutManager);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 状态栏沉浸
        StatusBarUtil.setColor(OnlineMusicAlbumActivity.this, getResources().getColor(android.R.color.holo_red_light), 0);//状态栏

        setContentView(R.layout.activity_online_music);
        recyclerView = findViewById(R.id.recyclerview);

        // 返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        Intent intent = getIntent();
        idx = intent.getIntExtra("idx", 0);
        name = intent.getStringExtra("name");
        setTitle(name);

        Toast.makeText(this, "正在获取音乐列表", Toast.LENGTH_SHORT).show();

        new GetMusicList().start();
    }

    @Override
    //点击actionBar返回
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return false;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    class GetMusicList extends Thread {
        @Override
        public void run() {
            super.run();
            Message message = new Message();
            message.obj = OnlineMusicUtils.getOnlineMusic(OnlineMusicAlbumActivity.this, idx);
            handler.sendMessage(message);
        }
    }
}
